package models

import (
	"errors"
	"github.com/jinzhu/gorm"
	"go.uber.org/zap"
)

type Tag struct {
	Model

	Name       string `json:"name"`
	CreatedBy  string `json:"created_by"`
	ModifiedBy string `json:"modified_by"`
	State      int    `json:"state"`
}

func GetTags(pageNum int, pageSize int, maps interface{}) ([]Tag, error) {
	var (
		tags []Tag
		err  error
	)
	if pageNum > 0 && pageSize > 0 {
		err = db.Where(maps).Offset(pageNum).Limit(pageSize).Find(&tags).Error
	} else {
		err = db.Where(maps).Find(&tags).Error
	}

	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		zap.L().Info("获取标签失败", zap.Error(err))
		return nil, err
	}

	return tags, nil
}

func GetTagTotal(maps interface{}) (int, error) {
	var count int
	if err := db.Model(&Tag{}).Where(maps).Count(&count).Error; err != nil {
		zap.L().Info("获取标签总数失败", zap.Error(err))
		return 0, err
	}
	return count, nil
}

func ExistTagByName(name string) (bool, error) {
	var tag Tag
	err := db.Select("id").Where("name = ? AND deleted_on = ?", name, 0).First(&tag).Error
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		zap.L().Info("通过名称判断标签是否存在失败", zap.Error(err))
		return false, err
	}
	if tag.ID > 0 {
		return true, nil
	}
	return false, nil
}

func AddTag(name string, state int, createdBy string) error {
	if err := db.Create(&Tag{
		Name:      name,
		State:     state,
		CreatedBy: createdBy,
	}).Error; err != nil {
		zap.L().Info("添加标签失败", zap.Error(err))
		return err
	}

	return nil
}

// BeforeCreate 新增操作，自动增加时间戳
//func (tag *Tag) BeforeCreate(scope *gorm.Scope) error {
//	err := scope.SetColumn("CreatedOn", time.Now().Unix())
//	if err != nil {
//		zap.L().Error("tag beforeCreate callback error", zap.Error(err))
//	}
//
//	return nil
//}

// BeforeUpdate 修改操作，自动增加时间戳
//func (tag *Tag) BeforeUpdate(scope *gorm.Scope) error {
//	err := scope.SetColumn("ModifiedOn", time.Now().Unix())
//	if err != nil {
//		zap.L().Error("tag beforeUpdate callback error", zap.Error(err))
//	}
//	return nil
//}

func ExistTagByID(id int) (bool, error) {
	var tag Tag
	err := db.Select("id").Where("id = ? AND deleted_on = ?", id, 0).First(&tag).Error
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		zap.L().Info("通过ID判断标签是否存在失败", zap.Error(err))
		return false, err
	}
	if tag.ID > 0 {
		return true, nil
	}
	return false, nil
}

func DeleteTag(id int) error {
	if err := db.Where("id = ?", id).Delete(&Tag{}).Error; err != nil {
		zap.L().Info("通过ID删除标签失败", zap.Error(err))
		return err
	}
	return nil
}

func EditTag(id int, data interface{}) error {
	if err := db.Model(&Tag{}).Where("id = ? AND deleted_on = ?", id, 0).Updates(data).Error; err != nil {
		zap.L().Info("编辑标签失败", zap.Error(err))
		return err
	}
	return nil
}

// CleanAllTag 硬删除代码
func CleanAllTag() (bool, error) {
	if err := db.Unscoped().Where("deleted_on != ? ", 0).Delete(&Tag{}).Error; err != nil {
		return false, err
	}
	return true, nil
}
